package com.zxing.encoding;

import java.util.Hashtable;

import android.graphics.Bitmap;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**
 * @author Ryan Tang
 * 
 */
public final class EncodingHandler {
	private static final int BLACK = 0xff000000;
	public static final int WHITE = 0xffffffff;// 白色
	public static final int BG_COLOR = 0xfff0f0f2;// 应用统一背景色
	private static int image_bg = 0xffffffff;// 二维码图片底色

	/**
	 * 生成二维码
	 * 
	 * @param str
	 *            二维码规则
	 * @param widthAndHeight
	 *            二维码宽、高
	 * @param bgcolor
	 *            二维码底色
	 * @return
	 * @throws WriterException
	 */
	public static Bitmap createQRCode(String str, int widthAndHeight,
			int bgcolor) throws WriterException {
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		// hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
		// hints.put(EncodeHintType. 1);

		image_bg = bgcolor;

		BitMatrix matrix = new MultiFormatWriter().encode(str,
				BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
		int width = matrix.getWidth();
		int height = matrix.getHeight();

		Log.i("QR", width + " : " + height);

		int[] pixels = new int[width * height];

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = BLACK;
				} else {
					pixels[y * width + x] = image_bg;
				}
			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}
}
